<?php

namespace addons\yunfood\model;

use addons\yunfood\library\ModelTrait;
use think\Cache;
use think\Db;
use think\Model;

/**
 * 配置模型
 */
class Config extends Model
{
    use ModelTrait;

    // 表名,不含前缀
    protected $name = 'yunfood_config';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = true;

    // 定义时间戳字段名
    protected $updateTime = 'updated_at';
    protected $createTime = 'created_at';

    protected $resultSetType = 'collection';

    // 分组
    const GROUP_BASE    = 'base';
    const GROUP_SMS     = 'sms';
    const GROUP_NOTICE  = 'notice';
    const GROUP_EXPRESS = 'express';
    const GROUP_MP      = 'mp';
    const GROUP_PRINT   = 'print';

    // 默认的H5域名
    public static function getDefaultH5Domain()
    {
        return request()->domain() . '/assets/addons/yunfood/h5/';
    }

    /**
     * @param false $cache
     * @return mixed
     */
    public static function getAllAttributes($cache = false)
    {
        return Cache::remember('config', function () {
            $configList = Config::where([])->select();

            $results = [];
            foreach ($configList as $item) {
                if (empty($results[$item['group']])) {
                    $results[$item['group']] = [];
                }
                $results[$item['group']][$item['key']] = $item['value'];
            }

            return $results;
        }, $cache ? 300 : 1);
    }

    /**
     * @param $attributes
     */
    public static function saveAllAttributes($attributes)
    {
        Db::transaction(function () use ($attributes) {
            foreach ($attributes as $group => $attribute) {
                foreach ($attribute as $key => $value) {
                    if (! $config = Config::get(compact('group', 'key'))) {
                        $config = new Config();
                        $config['group'] = $group;
                    }
                    $config['key'] = $key;
                    $config['value'] = trim($value);
                    $config->allowField(true)->save();
                    Cache::rm('config:' . $group . ':' . $key);
                }
                Cache::rm('config:' . $group);
            }
            Cache::rm('config');
        });
    }

    /**
     * @param $group
     * @param false $cache
     * @return mixed
     */
    public static function getGroupAttributes($group, $cache = false)
    {
        return Cache::remember('config:' . $group, function () use ($group) {
            $configList = Config::where(['group' => $group])->select();
            $results = [];
            foreach ($configList as $item) {
                $results[$item['key']] = $item['value'];
            }

            return $results;
        }, $cache ? 300 : 1);
    }

    /**
     * @param $group
     * @param $attributes
     */
    public static function saveGroupAttributes($group, $attributes)
    {
        Db::transaction(function () use ($group, $attributes) {
            foreach ($attributes as $key => $value) {
                if (! $config = Config::get(compact('group', 'key'))) {
                    $config = new Config();
                    $config['group'] = $group;
                }
                $config['key'] = $key;
                $config['value'] = trim($value);
                $config->allowField(true)->save();
                Cache::rm('config:' . $group . ':' . $key);
            }
            Cache::rm('config:' . $group);
            Cache::rm('config');
        });
    }

    /**
     * @param $group
     * @param $field
     * @param string $default
     * @param false $cache
     * @return mixed
     */
    public static function getGroupAttribute($group, $field, $default = '', $cache = false)
    {
        return Cache::remember('config:' . $group . ':' . $field, function () use ($group, $field, $default) {
            $config = Config::get(['group' => $group, 'key' => $field]);

            return $config ? $config['value'] : $default;
        }, $cache ? 300 : 1);
    }

    public static function getH5Domain()
    {
        $h5Domain = self::getGroupAttribute(self::GROUP_BASE, 'h5_domain');
        return trim($h5Domain ?: self::getDefaultH5Domain(), '/');
    }
}
